package com.uuah.server.config.spring.parsers.specific.endpoint.support;

import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.xml.ParserContext;
import org.w3c.dom.Element;

import com.uuah.server.config.spring.parsers.AbstractUuahBeanDefinitionParser;
import com.uuah.server.config.spring.parsers.generic.AutoIdUtils;
import com.uuah.server.config.spring.parsers.generic.ChildDefinitionParser;
import com.uuah.utils.StringUtils;

/**
 * A parser for "embedded" endpoints - ie request and response endpoints.
 * Because we have automatic String -> UuahEnpointURI conversion via property
 * editors this can be used in a variety of ways. single-element approach.
 *
 * <p>
 * This class does support references to other endpoints.
 * </p>
 * TODO - check that references are global!
 */
public class ChildEndpointDefinitionParser extends ChildDefinitionParser {

	public ChildEndpointDefinitionParser(Class endpoint) {
		super("endpoint", endpoint);
		addIgnored(AbstractUuahBeanDefinitionParser.ATTRIBUTE_REF);
		EndpointUtils.addProperties(this);
		EndpointUtils.addPostProcess(this);
	}

	// @Override
	public BeanDefinitionBuilder createBeanDefinitionBuilder(Element element,
			Class beanClass) {
		BeanDefinitionBuilder builder = super.createBeanDefinitionBuilder(
				element, beanClass);
		String global = element
				.getAttribute(AbstractUuahBeanDefinitionParser.ATTRIBUTE_REF);
		if (StringUtils.isNotBlank(global)) {
			builder.addConstructorArgReference(global);
			builder.addDependsOn(global);
		}
		return builder;
	}

	// @Override
	public String getBeanName(Element element) {
		if (null != element
				.getAttributeNode(AbstractUuahBeanDefinitionParser.ATTRIBUTE_REF)) {
			return AutoIdUtils
					.uniqueValue("ref:"
							+ element
									.getAttribute(AbstractUuahBeanDefinitionParser.ATTRIBUTE_REF));
		} else {
			return super.getBeanName(element);
		}
	}

	// @Override
	protected void parseChild(Element element, ParserContext parserContext,
			BeanDefinitionBuilder builder) {

		super.parseChild(element, parserContext, builder);
	}

}
